package com.yami.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.google.common.collect.Lists;
import com.yami.shop.bean.model.MeltCloudGroup;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.service.MeltCloudGroupService;
import com.yami.shop.service.MeltCloudGroupUserService;
import com.yami.shop.util.SendUtil;
import com.yami.shop.vo.group.UserIdVo;
import com.yami.shop.vo.group.gag.GroupGagVo;
import com.yami.shop.vo.group.gag.GroupGayRemVo;
import io.rong.RongCloud;
import io.rong.methods.group.gag.Gag;
import io.rong.methods.ultragroup.ban.User;
import io.rong.models.Result;
import io.rong.models.group.GroupMember;
import io.rong.models.group.GroupModel;
import io.rong.models.response.GroupUserQueryResult;
import io.rong.models.response.ListGagGroupUserResult;
import io.rong.models.ultragroup.UltraGroupMember;
import io.rong.models.ultragroup.UltraGroupModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.yami.shop.common.response.ServerResponseEntity.success;

/**
 * 群成员禁言
 */
@Service
@Slf4j
public class RongYunGagServiceImpl {
    @Autowired
    private RongCloud rongCloud;
    
    @Autowired
    private MeltCloudGroupService groupService;
    
    @Autowired
    private MeltCloudGroupUserService groupUserService;

    @Resource
    private DataSourceTransactionManager dataSourceTransactionManager;

    private Gag gag;
    
    private User ultraUserBan;

    @PostConstruct
    public void init() {
     gag =  rongCloud.group.gag;
     ultraUserBan = rongCloud.ultraGroup.user;
    }


    /**
     * 添加禁言群成员方法 一个或多个成员
     *
     * @param groupVo
     * @return
     */
    public ServerResponseEntity<String> add(GroupGagVo groupVo) throws Exception {
        MeltCloudGroup group = groupService.getById(groupVo.getGroupId());
        if (group == null || group.getIsDismiss().equals("1")) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该群不存在或已解散！");
        }
        List<UserIdVo> groups = groupVo.getUsers();
        List<String> userIds = groups.stream().map(UserIdVo::getId).collect(Collectors.toList());
        if (group.getType().equals("0")) {
            List<GroupMember> groupMembers = BeanUtil.copyToList(groups, GroupMember.class);
            GroupMember[] groupParam = groupMembers.toArray(new GroupMember[groupMembers.size()]);
            GroupModel param = new GroupModel()
                    .setId(groupVo.getGroupId())
                    .setMembers(groupParam)
                    .setMinute(groupVo.getMinute());
            Result result = gag.add(param);
            if (!SendUtil.requestSuccess(result)) {
                log.error("群聊禁言一个或多个成员方法异常", result.getErrorMessage());
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "群聊禁言失败");
            }
            groupUserService.taboo(groupVo.getGroupId(), userIds);
        } else {
            if (group.getIsArrears() == 1) {
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该超级群已欠费，不能操作！");
            }
            List<List<String>> partitions = Lists.partition(userIds, 20);
            for (List<String> users : partitions) {
                String userStr = users.stream().collect(Collectors.joining(","));
                UltraGroupMember member = new UltraGroupMember().setId(userStr);
                UltraGroupMember[] memberArr = new UltraGroupMember[]{member};
                UltraGroupModel param = new UltraGroupModel()
                        .setId(groupVo.getGroupId())
                        .setMembers(memberArr);
                Result result = ultraUserBan.add(param);
                if (!SendUtil.requestSuccess(result)) {
                    log.error("超级群聊禁言一个或多个成员失败", result.getErrorMessage());
                    throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "超级群聊禁言失败");
                }
                groupUserService.taboo(groupVo.getGroupId(), users);
            }
        }
        return success();
    }
    

    /**
     * 移除禁言群成员
     *
     * @param groupVo
     * @return
     */
    public ServerResponseEntity<String> remove(GroupGayRemVo groupVo) throws Exception {
        MeltCloudGroup group = groupService.getById(groupVo.getGroupId());
        if (group == null || group.getIsDismiss().equals("1")) {
            throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该群不存在或已解散！");
        }
        List<UserIdVo> groups = groupVo.getUsers();
        List<String> users = groups.stream().map(UserIdVo::getId).collect(Collectors.toList());
        if (group.getType().equals("0")) {
            List<GroupMember> groupMembers = BeanUtil.copyToList(groups, GroupMember.class);
            GroupMember[] groupParam = groupMembers.toArray(new GroupMember[groupMembers.size()]);
            GroupModel param = new GroupModel(groupVo.getGroupId(), groupParam, null, null);
            Result result = gag.remove(param);
            if (!SendUtil.requestSuccess(result)) {
                log.error("移除群聊禁言一个或多个成员方法异常", result.getErrorMessage());
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "移除群聊禁言失败");
            }
            groupUserService.cancelTaboo(groupVo.getGroupId(), users);
        } else {
            if (group.getIsArrears() == 1) {
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "该超级群已欠费，不能操作！");
            }
            List<List<String>> partitions = Lists.partition(users, 20);
            for (List<String> userIds : partitions) {
                String userStr = userIds.stream().collect(Collectors.joining(","));
                UltraGroupMember member = new UltraGroupMember().setId(userStr);
                UltraGroupMember[] memberArr = new UltraGroupMember[]{member};
                UltraGroupModel param = new UltraGroupModel()
                        .setId(groupVo.getGroupId())
                        .setMembers(memberArr);
                Result result = ultraUserBan.remove(param);
                if (!SendUtil.requestSuccess(result)) {
                    log.error("取消超级群聊禁言一个或多个成员失败", result.getErrorMessage());
                    throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "取消超级群聊禁言失败");
                }
                groupUserService.cancelTaboo(groupVo.getGroupId(), userIds);
            }
        }
        return success();
    }
    
    /**
     * 查询被禁言群成员
     *
     * @param groupId
     * @return
     */
    public ServerResponseEntity getList(String groupId) throws Exception {
        MeltCloudGroup group = groupService.getById(groupId);
        if (group.getType().equals("0")) {
            ListGagGroupUserResult result = gag.getList(groupId);
            if (SendUtil.requestSuccess(result))
                return success(result);
            throw new YamiShopBindException("查询群组禁言成员列表异常：" + result.getErrorMessage());
        } else {
            GroupUserQueryResult result = (GroupUserQueryResult) ultraUserBan.get(groupId);
            if (SendUtil.requestSuccess(result))
                return success(result);
            throw new YamiShopBindException("查询超级群组禁言成员列表异常：" + result.getErrorMessage());
        }
    }


    
}
